package com.lahuan.config.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Random;


@Aspect
@Component
public class DynamicDataSourceAspect {
    /**
     *  使用从库的方法名（匹配方法名开头）
     */
    String[] slaveMethodStart = {"select", "find","list","page","query","get"};

    /**
     * 匹配项目中 ServiceImpl为后缀的方法方法
     */
    @Pointcut(value = "execution(* com.lahuan..*.*ServiceImpl.*(..))  ")
    public void servicePointCut() {
    }

    @Around("servicePointCut()")
    public Object dynamicDataSourceAround(ProceedingJoinPoint joinPoint) throws Throwable {
        String name = joinPoint.getSignature().getName();
        System.out.println(name);
        String lookupKey = null;
        for (String start : slaveMethodStart) {
            if (name.startsWith(start)) {
                //路由 随机的方式
                lookupKey = routeSlave();
                break;
            }
        }

        DynamicRoutingDataSource.setLookupKey(lookupKey);
        try {
            return joinPoint.proceed();
        } finally {
            DynamicRoutingDataSource.removeLookupKey();
        }
    }

    /**
     * 数据源路由 随机的方式
     * @return
     */
    private String routeSlave() {
        return DataSourceConfig.SLAVE_LIST[new Random().nextInt(DataSourceConfig.SLAVE_LIST.length)];

    }


}
